<?php

/**
 * SigmaCMS - Content Management System
 *
 * Copyright (C) 2008 Pavol Biely
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    SigmaCMS
 * @author     Pavol Biely <pavolbiely@gmail.com>
 * @copyright  2008 Pavol Biely
 * @license    http://www.gnu.org/licenses/gpl.txt   GNU General Public License
 * @link       http://pabi3.com/
 * @since      0.1.0
 */

if (!defined('INSTALLATION')) die('Access denied!');

global $cfg;

/*** 0. step **********************************************************/
if (isset($_POST['step0'])) {
	header('Location:index.php?step=2');
	exit;
}

/*** 1. step **********************************************************/
else if (isset($_POST['step1'])) {
	// available languages
	$languages = $cfg['languages'];

	// load selected language
	$language = _post('language');

	// doest the selected language exist?
	if (!array_key_exists($language,$languages)) {
		$language = 'en';
	}

	$_SESSION['language'] = $language;
	header('Location:index.php?step=0');
	exit;
}

/*** 2. step **********************************************************/
else if (isset($_POST['step2'])) {
	if (!is_array(_post('dir'))) {
		die('Input must be an array.');
	}

	$dirs = array(
	'administration',
	'languages',
	'libraries',
	'logs',
	'plugins',
	'skins',
	'system',
	'temporary',
	'upload');

	$dirs = array_flip($dirs);
	$diff = array_diff_key($dirs,_post('dir'));

	// if the array keys are not equal, or there are more of them
	if (count($diff) != 0) {
		die('Only expected array input is accepted.');
	}

	$newdirs = _post('dir');

	foreach ($newdirs as $key => $dir) {
		$dir = trim(str_replace('\\','/',$dir));
		if ($dir{strlen($dir)-1} != '/') {
			$dir .= '/';
		}
		$newdirs[$key] = $dir;
	}

	$_SESSION['directories'] = $newdirs;
	header('Location:index.php?step=3');
	exit;
}

/*** 3. step **********************************************************/
else if (isset($_POST['step3'])) {
	if (!isset($_SESSION['directories'])) {
		die('Finish previous steps first.');
	}
	$general = array();

	// general
	$general['url']         = _post('url');
	$general['h1']          = _post('h1');
	$general['title']       = _post('title');
	$general['description'] = _post('description');
	$general['keywords']    = _post('keywords');
	$general['php']         = _post('php') ? 'true' : 'false';

	// add slash to the end of the URL, if it is not present
	$url = $general['url'];
	if ($url{strlen($url)-1} != '/') {
		$general['url'] .= '/';
	}

	// cookies
	$general['cookie_nameprefix'] = _post('cookie_nameprefix');
	$general['cookie_expiration'] = _post('cookie_expiration');
	$general['cookie_path']       = _post('cookie_path');
	$general['cookie_domain']     = _post('cookie_domain');
	$general['cookie_secure']     = _post('cookie_secure') ? 'true' : 'false';
	$general['cookie_httponly']   = _post('cookie_httponly') ? 'true' : 'false';

	$_SESSION['general'] = $general;
	header('Location:index.php?step=4');
	exit;
}

/*** 4. step **********************************************************/
else if (isset($_POST['step4'])) {
	if (!isset($_SESSION['directories'],$_SESSION['general'])) {
		die('Finish previous steps first.');
	}

	$dbType       = _post('type');
	$dbHost       = _post('host');
	$dbPort       = _post('port');
	$dbDatabase   = _post('database');
	$dbUsername   = _post('username');
	$dbPassword   = _post('password');
	$dbPrefix     = _post('prefix');
	$dbPersistent = _post('persistent') ? 'true' : 'false';

	if (!array_key_exists($dbType,$cfg['database'])) {
		die('An unsupported database type posted.');
	}

	$path = dirname(__FILE__).'/../'.$_SESSION['directories']['libraries'].'lib.db.php';
	if (file_exists($path)) {
		// emulate configuration class
		eval("
		class cfg {
			static protected \$_dbType       = '$dbType';
			static protected \$_dbHost       = '$dbHost';
			static protected \$_dbPort       = '$dbPort';
			static protected \$_dbDatabase   = '$dbDatabase';
			static protected \$_dbUsername   = '$dbUsername';
			static protected \$_dbPassword   = '$dbPassword';
			static protected \$_dbPrefix     = '$dbPrefix';
			static protected \$_dbPersistent = $dbPersistent;
		}
		");

		$database = array(
		'type'       => $dbType,
		'host'       => $dbHost,
		'port'       => $dbPort,
		'database'   => $dbDatabase,
		'username'   => $dbUsername,
		'password'   => $dbPassword,
		'prefix'     => $dbPrefix,
		'persistent' => $dbPersistent
		);

		// save database settings to session
		$_SESSION['database'] = $database;

		// include class for database connection
		include_once $path;
		include_once './databases/'.$dbType.'.php';

		// test connection
		try {
			// try to create database
			if (isset($_POST['create'])) {
				switch ($dbType) {
					case 'mysql':
						$db = @mysql_connect($dbHost,$dbUsername,$dbPassword);
						if (!@mysql_query("CREATE DATABASE ".$dbDatabase,$db)) {
							throw new Exception('Cannot create a database (MySQL)');
						}
						@mysql_close($db);
						break;
					case 'mysqli':
						$db = @mysqli_connect($dbHost,$dbUsername,$dbPassword);
						if (!@mysqli_query($db,"CREATE DATABASE ".$dbDatabase)) {
							throw new Exception('Cannot create a database (MySQLi)');
						}
						@mysqli_close($db);
						break;
					case 'mssql':
						$db = @mssql_connect($dbHost,$dbUsername,$dbPassword);
						if (!@mssql_query("CREATE DATABASE ".$dbDatabase,$db)) {
							throw new Exception('Cannot create a database (Microsoft SQL Server)');
						}
						@mssql_close($db);
						break;
					case 'fbsql':
						break;
						$db = @fbsql_connect($dbHost,$dbUsername,$dbPassword);
						if (!@fbsql_query("CREATE DATABASE ".$dbDatabase,$db)) {
							throw new Exception('Cannot create a database (FrontBase)');
						}
						@fbsql_close($db);
					break;
				}
			}

			// connect to database
			db::initialize();

			// create tables and insert data
			CreateTables::begin();

			// is database connection established?
			if (db::isConnected()) {
				header('Location:index.php?step=5');
				exit;
			} else {
				throw new Exception('Cannot establish database connection.');
			}
		} catch (Exception $e) {
			die($e->getMessage());
		}
	} else {
		die('Cannot test database connection, because class DB was not found.');
	}
}

/*** 5. step **********************************************************/
else if (isset($_POST['step5'])) {
	if (!isset($_SESSION['database'],$_SESSION['directories'],$_SESSION['general'])) {
		die('Finish previous steps first.');
	}
$conf = <<<CONF
<?php

/**
 * SigmaCMS - Content Management System
 *
 * Copyright (C) 2008 Pavol Biely
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    SigmaCMS
 * @author     Pavol Biely <pavolbiely@gmail.com>
 * @copyright  2008 Pavol Biely
 * @license    http://www.gnu.org/licenses/gpl.txt   GNU General Public License
 * @link       http://pabi3.com/
 * @since      0.1.0
 */

abstract class cfg
{
	// absolute URL ending with a slash!
	const URL = '{$_SESSION['general']['url']}';

	// directory structure
	const DIR_ADMIN   = '{$_SESSION['directories']['administration']}';
	const DIR_LANGS   = '{$_SESSION['directories']['languages']}';
	const DIR_LIBS    = '{$_SESSION['directories']['libraries']}';
	const DIR_LOGS    = '{$_SESSION['directories']['logs']}';
	const DIR_PLUGINS = '{$_SESSION['directories']['plugins']}';
	const DIR_SKINS   = '{$_SESSION['directories']['skins']}';
	const DIR_SYSTEM  = '{$_SESSION['directories']['system']}';
	const DIR_TMP     = '{$_SESSION['directories']['temporary']}';
	const DIR_UPLOAD  = '{$_SESSION['directories']['upload']}';

	// database access
	static protected \$_dbType       = '{$_SESSION['database']['type']}';
	static protected \$_dbHost       = '{$_SESSION['database']['host']}';
	static protected \$_dbPort       = '{$_SESSION['database']['port']}';
	static protected \$_dbDatabase   = '{$_SESSION['database']['database']}';
	static protected \$_dbUsername   = '{$_SESSION['database']['username']}';
	static protected \$_dbPassword   = '{$_SESSION['database']['password']}';
	static protected \$_dbPrefix     = '{$_SESSION['database']['prefix']}';
	static protected \$_dbPersistent = {$_SESSION['database']['persistent']};

	// prefix for admin files
	const ADMIN_PREFIX  = 'admin.';

	// prefix for plugins
	const PLUGIN_PREFIX = 'plugin.';
	
	// PHP analyzing
	const PARSE_PHP = {$_SESSION['general']['php']};

	// SigmaCMS version; do not change!
	const VERSION = '0.1.0-svn';

	/**
	 * Return configuration directive
	 *
	 * @param string \$name
	 * @return string
	 */
	static public function get(\$name)
	{
		// result of this method will be saved to cache
		static \$_cfgCache = array();

		// is the directive in the cache?
		if (!array_key_exists(\$name, \$_cfgCache)) {
			\$sql = db::query("SELECT `name`,`value` FROM ".db::prefix('configuration'));
			while (\$row = db::fetchObject(\$sql)) {
				\$_cfgCache[\$row->name] = \$row->value;
			}
			db::free(\$sql);
		}

		return \$_cfgCache[\$name];
	}
}

// global system functions, error reporting, exception handling
require_once dirname(__FILE__).'/'.cfg::DIR_SYSTEM.'sys.global.php';
require_once dirname(__FILE__).'/'.cfg::DIR_SYSTEM.'sys.exceptions.php';

// classes
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.log.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.i18n.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.db.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.action.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.media.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.member.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.driver.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.parser.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.template.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.element.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.ftp.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.plugin.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.plugin.api.php';
require_once dirname(__FILE__).'/'.cfg::DIR_LIBS.'lib.main.php';
CONF;

	$path = dirname(__FILE__).'/../configuration.php';

	if (file_exists($path)) {
		die('You have already created the /configuration.php file. Delete it if you want to install your system again.');
	}

	@chmod($path,0777);
	if (file_put_contents($path,$conf) == 0) {
		die('The /configuration.php file is not writeable. Please set its CHMOD to 0777 (only for this action).');
	}

	$_SESSION = array();
	header('Location:../');
	exit;
}
